package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.Result
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.LogUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class FabulousRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL).addConverterFactory(
                GsonConverterFactory.create()
            )
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    fun saveFabulousById(userId: Int, articleId: Int): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.saveMyLikeByID(mapOf("sfNumber" to userId, "articleId" to articleId))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        responseLiveData.value = it
                    } ?: LogUtils.e("保存点赞http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }
            })
        return responseLiveData
    }

    fun cancelFabulousById(userId: Int, articleId: Int): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.cancelMyLikeByID(mapOf("sfNumber" to userId, "articleId" to articleId))
            .enqueue(object : Callback<Result> {
                override fun onResponse(call: Call<Result>, response: Response<Result>) {
                    response.body()?.let {
                        responseLiveData.value = it
                    } ?: LogUtils.e("取消点赞http返回值为空！")
                }

                override fun onFailure(call: Call<Result>, t: Throwable) {
                    LogUtils.e(t)
                }
            })
        return responseLiveData
    }
}